Some PHP Coding Tips of php tips [2011 and 04 and 02 last updated]

  • 2020-05-05 11:03:15
  • OfStack

Last updated: 2011/04/02

1. Use list to get the specific segment value after explode once:
list( , $mid) = explode(';', $string);
2. NULL === instead of is_null:
is_null is exactly the same as NULL ===, but it saves a function call to.

3. Use === instead of ==:
PHP has two sets of equal comparison operators ===/! = = and = = /! = = = /! = will have implicit type casting, and === =/! == strictly compares two operations with the same type and the same value.
We should try to use === instead of ==, in addition to the fact that the conversion rules are hard to remember, there is also a point where if you use ===, you will be comfortable with future maintenance or people reading your code: "at this point, this line of statement, this variable is of this type!" .

Use continue sparingly:
continue is going back to the head of the loop, and the end of the loop is going back to the head of the loop, so with proper construction, we can completely avoid using this statement, resulting in improved efficiency
5. Beware of loose comparisons of switch/in_array, etc. (loose comparision):
switch and in_array are both loosely compared, so it's easy to make an error when the types of variables to be compared are different:

 
switch ($name) { 
case "laruence": 
... 
break; 
case "eve": 
... 
break; 
} 

For switch above, if $name is the number 0, it satisfies any case. The same is true for in_array.
The solution is, before switch, to convert the variable type to the type you expect.
 
switch (strval($name)) { 
case "laruence": 
... 
break; 
case "eve": 
... 
break; 
} 


However, in_array provides a third optional parameter through which the default comparison mode can be changed.
6. switch is not just used to identify variables:
For example, for the following piece of code:
 
if($a) { 
} else if ($b) { 
} else if ($c || $d) { 
} 

This can be simply rewritten as
 
switch (TRUE) { 
case $a: 
break; 
case $b: 
break; 
case $c: 
case $d: 
break; 
} 

Does it look clearer?
7. Define variables before using:
Using an undefined variable is more than 8 times slower than using a defined variable!
As you can imagine, the PHP engine will first follow the normal logic to get the variable, but the variable does not exist, so the PHP engine needs to throw an NOTICE, enter the logic that should be used when using an undefined variable, and then return a new variable.
In addition, from a code reading perspective, when you use an undefined variable, the reader of your code is left wondering, "does the variable initialized there have anything to do with the previous code? Does it have anything to do with the files that include came in?"
Finally, from a formal programming perspective, you need to do the same 8. Exchange the values of two variables without using the third variable:
list($a, $b) = array($b, $a),
However, there is still the generation of anonymous temporary variables, for the integer, using the operation of mutual inverse, or more reliable:
 
$a = $a + $b; 
$b = $a - $b; 
$a = $a - $b; 

However, it is better to use xor, because + * / can easily cause precision loss or overflow.
9. floor == two non-operations (this is provided by skiyo)
 
echo ~~4.9; 
echo floor(4.9); 

The speed of two non-operations is basically three times that of floor, but there is one point where an overflow can occur for large Numbers:
 
echo ~~99999999999999.99; //276447231 
echo floor(99999999999999.99); //99999999999999 

10. do{}while(0) charm (this article is provided by Qianfeng)
We know that do{}while(0) has many clever USES in c/c++, such as eliminating goto, macros defining code blocks.
So, in PHP, you can also use do{}while(0) to do some clever applications of
 
do{ 
if(true) { 
break; 
} 
if(true) { 
break; 
} 
} while(false); 
// Better than  
if(true) { 
} else if(true) { 
} else { 
} 

11. Use the @ error suppressor
sparingly The following code:
 
@func(); 

This is equivalent to (see in-depth understanding of PHP principle of error suppression and embedded HTML):
 
$report = error_reporting(0); 
func(); 
error_reporting($report); 

Additional error suppression symbol, may cause some problems, see (/ / www. jb51. net article / 27022. htm);
Finally, the error suppressor can also cause problems when debugging errors occur Try to avoid recursion (this is from lazyboy)
Recursion performance is worrying, and most recursion is tail recursion, which can be eliminated
 
function f($n) { 
if ($n = 0) return 1; 
return $n * f($n - 1); 
} 
// into : 
$result = 1; 
for ($y = 1; $y < $n + 1; $y++ ) { 
$result *= $y; 
} 

13. Use $_SERVER['REQUEST_TIME'] instead of time()
time() will cause a function call, but if the exact value of the time is not required, you can use $_SERVER['REQUEST_TIME'] instead, which is much faster 14. Avoid operating in for judgment conditions (this is from Anonymous in the comment)
The following code:
for($i=0; $i < strlen($str); $i++) {
}
This causes strlen to be called every time in the loop, changing to
for ($i=0, $j=strlen($str); $i < $j; $i++) {
}
15. Try to avoid regular (this is from pangyontao)
Regex takes time to avoid, and instead USES a direct string handler such as
 
if (preg_match("!^foo_!i", "FoO_")) { } 
//  Replace with : 
if (!strncasecmp("foo_", "FoO_", 4)) { } 
if (preg_match("![a8f9]!", "sometext")) { } 
//  Replace with : 
if (strpbrk("a8f9", "sometext")) { } 
if (preg_match("!string!i", "text")) {} 
//  Replace with : 
if (stripos("text", "string") !== false) {} 

And so on.
16. Use curly braces to enclose the variable
in double quotes and heredoc The following code:
echo "$name[2]";
PHP does not know whether the programmer's intent is $name. "[2]" or $name[2],
So it is recommended that you put braces:
 
echo "{$name}[2]"; 
// or  
echo "${name}[2]"; 

17. FALSE for error, NULL for nonexistence.
For functions of the operation class, failure returns FALSE for "operation failed", while for functions of the query class, if the desired value cannot be found, NULL for "cannot be found" should be returned.

Related articles: